package com.lijia.ffmpeg4android.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.lijia.ffmpeg4android.intent.CrimeIntentJSONSerializer;

import android.content.Context;
import android.util.Log;

public class CrimeLab {
	private static final String FILENAME = "Crimes.json";
	private static final String TAG = "CrimeLab";
	
	private static CrimeLab sCrimeLab;
	private Context mAppContext;
	private List<Crime> mCrimes;
	private CrimeIntentJSONSerializer mSerializer;

	private CrimeLab() {
		
	}
	
	private CrimeLab(Context appContext) {
		this.mAppContext = appContext;
		this.mCrimes = new ArrayList<Crime>();
		this.mSerializer = new CrimeIntentJSONSerializer(appContext, FILENAME);
		
		Date nowDate = new Date();
		for (int i = 0; i < 100; i++) {
			Crime c = new Crime();
			c.setTitle("Crime #" + i);
			c.setSolved(i % 2 == 0);
			c.setDate(nowDate);
			this.mCrimes.add(c);
		}
		
//		try {
//			mCrimes = mSerializer.loadCrimes();
//		} catch (Exception e) {
//			mCrimes = new ArrayList<Crime>();
//			e.printStackTrace();
//		}
	}
	
	public static CrimeLab get(Context c) {
		if(sCrimeLab == null) {
			sCrimeLab = new CrimeLab(c.getApplicationContext());
		}
		return sCrimeLab;
	}
	
	public void deleteCrime(Crime c) {
		mCrimes.remove(c);
	}
	
	public boolean saveCrimes() {
		try {
			mSerializer.saveCrimes(mCrimes);
			Log.d(TAG, "crimes saved to file");
			return true;
		} catch (Exception e) {
			Log.e(TAG, "Error saving crimes: ",e);
			return false;
		} 
	}
	
	public boolean saveCrimesToExternal() {
		try {
			mSerializer.saveCrimes(mCrimes);
			Log.d(TAG, "crimes saved to file");
			return true;
		} catch (Exception e) {
			Log.e(TAG, "Error saving crimes: ",e);
			return false;
		} 		
	}

	public List<Crime> getCrimes() {
		return mCrimes;
	}
	
	public Crime getCrime(UUID id) {
		if(null == id) {
			return null;
		}
		
		for (Crime c : mCrimes) {
			if(c.getId().equals(id)) {
				return c;
			}
		}
		return null;
	}
	
	public int getCrimeIndex(UUID id) {
		int index = -1;
		if(null == id) {
			return index;
		}
		
		for (int i = 0;i < mCrimes.size(); ++i) {
			if(mCrimes.get(i).getId().equals(id)) {
				index = i;
				break;
			}
		}		
		
		return index;
	}
}
